# -*- coding: utf-8 -*-
# Create your views here.
import logging
from django.shortcuts import render_to_response
from django.template.context import RequestContext
import os
from django.http import HttpResponse
import datetime
from google.appengine.ext import db
from com.jumang.model import note
from com.jumang.model import uploadfile,uploadpicture
from django.http import HttpResponsePermanentRedirect
from django.http import HttpResponse
from com.jumang.client.forms import NoteCommentForm,FileCommentForm,PictureCommentForm,MessageForm
from appengine_utilities.sessions import Session
from config import JumConfig,realConfig

def checkSpam(content,subString='http://',count=4):
  if content.lower().count(subString)>4:
    return False
  else:
    return True

def addNoteComment(request):
    form=NoteCommentForm(request.POST)
    if form.is_valid():
        comment=form.save(commit=False)
        if checkSpam(comment.content):
          comment.note=note.note.get_by_id(int(request.POST['id']))
          comment.put()
        return HttpResponsePermanentRedirect('/main/note/?id=%s' %request.POST['id'])
    return HttpResponsePermanentRedirect('/')
    
def addFileComment(request):
    form=FileCommentForm(request.POST)
    if form.is_valid():
        comment=form.save(commit=False)
        if checkSpam(comment.content):
          comment.mfile=uploadfile.file.get_by_id(int(request.POST['id']))
          comment.put()
        return HttpResponsePermanentRedirect('/main/file/?id=%s' %request.POST['id'])
    return HttpResponsePermanentRedirect('/')
        
def addMessage(request):
    form=MessageForm(request.POST)
    if form.is_valid():
        comment=form.save(commit=False)
        if checkSpam(comment.content) and checkSpam(comment.content,'href'):
          comment.put()
        return HttpResponsePermanentRedirect('/main/messages/')
    return HttpResponsePermanentRedirect('/')
    
def addPictureComment(request):
    form=PictureCommentForm(request.POST)
    if form.is_valid():
        comment=form.save(commit=False)
        if checkSpam(comment.content):
          comment.picture=uploadpicture.Picture.get_by_id(int(request.POST['id']))
          comment.put()
        return HttpResponsePermanentRedirect('/main/picture/?id=%s' %request.POST['id'])
    return HttpResponsePermanentRedirect('/')

def login(request):
  code=unicode(request.POST["verificationCode"],'utf-8')
  if code==realConfig.getPrivatePwd():
    session=Session()
    session['checked']=True
  return HttpResponsePermanentRedirect('/')
    
  
  
def logout(request):
  session=Session()
  session.delete()
  return HttpResponsePermanentRedirect('/')

  
